import {
  getSetting,
  openSetting,
  chooseAddress,
  showModal,
  showToast
} from '../../utils/util';

Page({
  data: {
    address: {},
    carts: [],
    all_select: true,
    total_price: 0,
    total_num: 0
  },
  onShow() {
    this.pageInit();
  },
  handleChooseAddress: async function () {
    try {
      let { authSetting } = await getSetting();
      if (authSetting["scope.address"] === false) {
        await openSetting();
      }
      let address = await chooseAddress();
      let { provinceName, cityName, countyName, detailInfo } = address;
      address.all = provinceName + cityName + countyName + detailInfo;
      wx.setStorageSync('address', address);
    } catch (error) {
      console.log(error);
    }
  },
  pageInit() {
    let address = wx.getStorageSync('address');
    let carts = wx.getStorageSync('carts') || [];

    this.setData({
      address
    });
    this.setCart(carts);
  },
  // 实现单选时，对全选的影响
  handelSelect(e) {
    let index = e.detail.index;
    let carts = this.data.carts;

    carts[index].is_select = !carts[index].is_select;

    this.setCart(carts);
  },
  // 实现全选时对单选的影响
  handelSelectAll() {
    let { carts, all_select } = this.data;
    all_select = !all_select;

    carts.forEach(item => item.is_select = all_select);

    this.setCart(carts);
  },
  // 设置购物车的全选、价格、数量
  setCart(carts) {
    let total_num = 0, total_price = 0;
    let all_select = carts.length === 0 ? false : true;

    carts.forEach(v => {
      if (v.is_select) {
        total_num += v.num;
        total_price += v.num * v.goods_price;
      } else {
        all_select = false;
      }
    });
    this.setData({
      all_select, carts, total_num, total_price
    });
    wx.setStorageSync('carts', carts);
  },
  // 商品的数量变化以及删除
  handleNumEdit: async function (e) {
    let { operation, index } = e.detail;
    let { carts } = this.data;
    carts[index].num += operation;

    if (carts[index].num === 0) {
      let res = await showModal('你是否确定删除该商品？');

      if (res.confirm) {
        carts.splice(index, 1);
      } else {
        carts[index].num = 1;
        return;
      }
    }
    this.setCart(carts);
  },
  handleShopping: async function () {
    if (!this.data.address) {
      await showToast('请选择收货地址！');
      return;
    }
    if (this.data.total_num === 0) {
      await showToast('请选择需要购买的商品!');
      return;
    }
    wx.navigateTo({
      url: '/pages/pay/pay'
    });
  }
})